<template>
	<div class="pos">
		<left-nav></left-nav>
		<div class="pos-main"> 
			<el-row> 
				
				<!-- 待支付订单结构代码，后面再添加 -->
				<el-col :span="17" id="goods-list"> 
					<el-col :span='7' class="post-list" id="order-list">
						<el-tabs v-model="activeName" @tab-click="handleClick">
							<el-tab-pane label="点餐" name="first"> 
								<el-table :data="tableData" border style="width: 100%" >
								<el-table-column prop="goodsName" label="商品" ></el-table-column>
								<el-table-column prop="count" label="数量" align="center" width="50"></el-table-column>
								<el-table-column prop="price" label="金额" align="center" width="70"></el-table-column> 
								<el-table-column label=" 操 作" width="100" fixed="right" align="center"> 
									<template slot-scope="scope">
										<el-button type="text" size="small" @click="delSingleGoods(scope.row)">删除</el-button> 
									</template> 
								</el-table-column>
								</el-table> 
								<p style="text-align:right;padding-right:10px">数量：{{totalCount}} 总 价：{{totalMoney}}元</p>
								<!-- 三个按钮 -->
								<div class="btn-group">
									<el-button type="danger" @click="delAllGoods">清空</el-button>
									<el-button type="success" @click="checkout">结账</el-button> 
								</div> 
							</el-tab-pane> 
							<el-tab-pane label="订单列表" name="second"> 
								<div class="orderlist"> 
									<div class="order" v-for="(order,index) in orderList"> 
										<div class="order-hd"> 
											订单编号：{{order._id}} 
											<span>订单总价：{{order.ordertotal}}元</span>
										</div> 
										<div class="goods-info">
											<table class="order-table" cellpadding="0" cellspacing="0"> 
												<tr>
													<td>商品名称</td>
													<td>商品数量</td> 
													<td>商品单价</td> 
												</tr> 
												<tr v-for="goodsInfo in order.goodslist"> 
													<td>{{goodsInfo.orderName}}</td>
													<td>{{goodsInfo.orderNum}}</td>
                                                    <td>{{goodsInfo.orderPrice}}</td> 
												</tr> 
											</table> 
										</div> 
									</div>
								</div> 
							</el-tab-pane> 
						</el-tabs>
					</el-col> 
					
					<!-- 常用商品结构代码，后面再添加 --> 
					<div class="often-goods">
						<div class="title">常用商品</div> 
						<div class="often-goods-list"> 
							<ul> 
								<li v-for="goods in oftenGoods" @click="addOrderList(goods)"> 
									<span>{{goods.goodsName}}</span>
									<span class="o-price">￥{{goods.price}}元</span> 
								</li>
							</ul> 
						</div> 
					</div>
					<div class="goods-type"> 
						<el-tabs>
							<el-tab-pane label="汉堡">
								<ul class='cookList'> 
									<li v-for="goods in type1Goods" @click="addOrderList(goods)">
										<span class="foodImg"><img :src="imgUrl+goods.goodsImg" width="100%"></span>
										<span class="foodName">{{goods.goodsName}}</span> <span class="foodPrice"> ￥ {{goods.price}} 元 </span> 
									</li>
								</ul>
							</el-tab-pane> 
							<el-tab-pane label="主食">
								<ul class='cookList'> 
									<li v-for="goods in type2Goods" @click="addOrderList(goods)"> 
										<span class="foodImg"><img :src="imgUrl+goods.goodsImg" width="100%"></span> 
										<span class="foodName">{{goods.goodsName}}</span> 
										<span class="foodPrice">￥{{goods.price}}元</span> 
									</li> 
								</ul>
							</el-tab-pane> 
							<el-tab-pane label="饮料">
								<ul class='cookList'> 
									<li v-for="goods in type3Goods" @click="addOrderList(goods)"> 
										<span class="foodImg"><img :src="imgUrl+goods.goodsImg" width="100%"></span> 
										<span class="foodName">{{goods.goodsName}}</span>
										<span class="foodPrice">￥{{goods.price}}元</span> 
									</li> 
								</ul> 
							</el-tab-pane> 
						</el-tabs> 
					</div> 
				</el-col> 
			</el-row> 
		</div>
	</div>
</template>

<script>
	import LeftNav from '@/components/common/LeftNav' // 导入左侧组件 
	export default {
		name: 'Pos',
		components:{
			LeftNav 
		}, 
		data () {
			return { 
				type1Goods:[],
				type2Goods:[], 
				type3Goods:[],
				oftenGoods:[],
				activeName: 'first', 
				totalMoney:0, 
				totalCount:0, 
				tableData:[], // 待支付数组 
				orderList:[] // 订单详情数组（提交给服务端）

			} 
		}, 
		created(){ 
			//向服务端发送请求，读取分类商品列表
			this.$http.get('/goodslist')
			.then(response=>{ 
				this.type1Goods=response.data.list.type1;
				this.type2Goods=response.data.list.type2;
				this.type3Goods=response.data.list.type3; 
			})
			.catch(error=>{ 
				alert('网络错误，不能访问'); 
			})
			
			this.$http.get('/goodsofftenlist',{ // 获取常用商品列表 
				params:{ 
					num:10, 
				} 
			}) 
			.then(response=>{
				this.oftenGoods=response.data.list; 
			})
			.catch(error=>{ 
				this.$message('网络连接失败,请稍候再试！') 
				this.$router.push('/')
			})
		},
		methods:{
			//添加待支付订单功能
			addOrderList(goods){ 
				this.goodsList=[]; 
				this.totalCount=0; //汇总数量清0 
				this.totalMoney=0; 
				let isHave=false;
				//判断是否这个商品已经存在于订单列表
				for (let i=0; i<this.tableData.length;i++){
					if(this.tableData[i].goodsId==goods._id){
						isHave=true; //存在 
					} 
				} 
				//根据isHave 的值判断订单列表中是否已经有此商品
				if(isHave){
					//存在就进行数量添加 
					let arr = this.tableData.filter(o =>o.goodsId == goods._id);
					arr[0].count++;
				}else{ 
					//不存在就推入数组
					let newGoods={goodsId:goods._id,goodsName:goods.goodsName,price:goods.price,count:goods.count}; 
					this.tableData.push(newGoods);
				}
				this. getAllMoney() // 执行价格统计
			},
			
			//删除单个商品
			delSingleGoods(goods){ 
				this.tableData=this.tableData.filter(o => o.goodsId != goods.goodsId); 
				this.getAllMoney() 
			},
			
			// 数量汇总和金额 
			getAllMoney(){ 
				this.totalCount=0; 
				this.totalMoney=0;
				if(this.tableData){ 
					this.tableData.forEach(element => { 
						this.totalCount+=element.count;
						this.totalMoney=this.totalMoney+(element.price*element.count); 
					});
				}
			},
			
			// 删除所有商品
			delAllGoods() { 
				this.tableData = []; // 清空待支付订单 
				this.totalCount = 0; // 设置商品总数为0 
				this.totalMoney = 0; // 设置总金额为0 
			},
			
			// 订单提交功能 
			checkout() { // 提交订单
                if (this.totalCount!=0) { 
                	for (let i = 0; i < this.tableData.length; i++) {
                		var goodsArr = {orderName:this.tableData[i].goodsName,orderNum:this.tableData[i].count,orderPrice:this.tableData[i] .price} 
                		this.orderList.push(goodsArr) 
                	} 
                	this.$http.post('/orderlistAdd',{ // 向服务端提交订单 
                		tokenid:localStorage.getItem('tokenID'),
                		username:localStorage.getItem('userName'), 
                		orderList:this.orderList, 
                		orderTotal:this.totalMoney 
                	})
                	.then(response=>{ // 提交订单完成后重置待支付订单 
                		this.tableData = []; 
                		this.totalCount = 0; 
                		this.totalMoney = 0; 
                		this.orderList = [];
                		this.$message({ 
                			message: '结账成功，欢迎下次光临!',
                			type: 'success'
                		}); 
                		this.orderListGet() // 提交完成后需要重新获取已支付订单（暂未实现）
                	}) 
                } else{
                	this.$message.error('未选择商品，下单失败！'); 
                } 
			},
			
			//订单查询功能
			orderListGet(){ // 获取订单列表
				this.$http.post('/orderlistGet',{ 
					tokenid:localStorage.getItem('tokenID'), 
					username:localStorage.getItem('userName')
				}) 
				.then(response=>{ 
					this.orderList = response.data.list 
					console.log(response) 
				}) 
				.catch(error=>{
					this.$message.error('网络问题，订单列表读取失败！'); 
				})
			},
			handleClick(tab, event) {
		        console.log(tab, event);
		    }
		},
		mounted:function(){ 
			this.orderListGet() // 执行订单查询函数
		}
	}
	// 访问授权验证
	beforeRouteEnter: (to, from, next) => {
		var checkTokenID=localStorage.getItem('tokenID') 
		if (!checkTokenID) { 
			next('/') 
		} else{ 
			next()
		}
    }
</script>

<style>
	/*右边两部分*/
	.pos-main{
		float: left;
	}
	#goods-list{
		float: right;
		overflow:hidden;
		width: 1125px;
	}
	/*右边的左部*/
	.post-list{
		float: left;
		width: 35%;
		background: white;
		border-right: 2px solid #e4e7ed;
		height: 753px;
		padding-left: 2px;
		
	}
	 /*右边左部的按钮*/
	.btn-group{
		text-align: center;
		margin-top: 10px;
	}
	/*常用商品（右边的右上部）*/
	.often-goods{
		float: right;
		width: 65%;
	}
	.often-goods .title{
		background: white;
		padding: 10px;
	}
	.often-goods-list ul{
		overflow: hidden;
		padding: 10px 25px;
	}
	.often-goods-list ul li{
		float: left;
		background: white;
		padding: 5px;
		margin: 5px;
		border-radius: 3px;
	}
	.often-goods-list ul li span:last-child{
		color: #81cfe7;
	}
	/*汉堡 主食 饮料（右边的右下部）*/
	.goods-type{
		float: right;
		width: 65%;
		padding: 0 10px;
	}
	.cookList{
		overflow: hidden;
	}
	.cookList li{
		width: 190px;
		overflow: hidden;
		float: left;
		background: white;
		margin:0 10px 10px 0;
	}
	.cookList li .foodImg{
		float: left;
		width: 90px;
		height: 90px;
	}
	.cookList li .foodName{
		float: left;
		margin-left: 10px;
		color: #f62350;
	}
	.cookList li .foodPrice{
		float: left;
		margin:5px 0 0 10px;
		
	}
</style>